<template>
	<view>
		<movable-area class="movable-area" :scale-area="false">
			<movable-view class="movable-view" :class="!data.isRemove?'animation-info':''" style="pointer-events: auto;"
				@click="clickBtn" @touchstart="touchstart" @touchend="touchend" @change="onChange" direction="all"
				inertia="true" :x="data.x" :y="data.y" :disabled="disabled" :out-of-bounds="true" :damping="200"
				:friction="100">
				<slot></slot>
			</movable-view>
		</movable-area>
	</view>
</template>

<script setup>
	import {
		reactive,
		onMounted
	} from 'vue';
	const props = defineProps({
		//是否禁用拖动
		disabled: {
			type: Boolean,
			default: false
		},
		//是否自动停靠
		canDocking: {
			type: Boolean,
			default: true
		},
		//按钮默认位置离底部距离（px）
		bottomPx: {
			type: Number,
			default: 30
		},
		//按钮默认位置离右边距离（px）
		rightPx: {
			type: Number,
			default: 0
		},
	})

	const emit = defineEmits(['updateItemLocal','clickBtn'])
	const data = reactive({
		left: 0,
		top: 0,
		isRemove: true,
		windowWidth: 0,
		windowHeight: 0,
		btnWidth: 0,
		btnHeight: 0,
		x: 10000,
		y: 10000,
		old: {
			x: 0,
			y: 0
		}
	})
	import {
		getCurrentInstance
	} from 'vue'
	const instance = getCurrentInstance()

	function getSysInfo() {
		let sysInfo = uni.getSystemInfoSync()
		data.windowWidth = sysInfo.windowWidth
		data.windowHeight = sysInfo.windowHeight
		let view = uni.createSelectorQuery().in(instance).select(".movable-view")
		view.boundingClientRect(rect => {
			data.btnWidth = rect.width
			data.btnHeight = rect.height
			data.x = data.old.x
			data.y = data.old.y
			instance.proxy.$nextTick(res => {
				data.x = data.windowWidth - data.btnWidth - props.rightPx
				data.y = data.windowHeight - data.btnHeight - props.bottomPx
			})
		}).exec()
	}

	onMounted(() => {
		getSysInfo()
	})
	//移动按钮
	function onChange(e) {
		data.old.x = e.detail.x
		data.old.y = e.detail.y
	}
	//开始移动
	function touchstart(e) {
		data.isRemove = true
	}
	//结束移动
	function touchend(e) {
		if (props.canDocking && data.old.x) {
			data.x = data.old.x
			data.y = data.old.y
			let bWidth = (data.windowWidth - data.btnWidth) / 2
			if (data.x < 0 || (data.x > 0 && data.x <= bWidth)) {
				instance.proxy.$nextTick(res => {
					data.x = 0
					emit('updateItemLocal', -1)
				})
			} else {
				instance.proxy.$nextTick(res => {
					data.x = data.windowWidth - data.btnWidth
					emit('updateItemLocal', 1)
				})
			}
			data.isRemove = false
		}
	}
	//点击按钮
	function clickBtn() {
		emit('clickBtn')
	}
</script>

<style scoped>
	.movable-view {
		width: 180px;
		height: 80px;
		border-radius: 50px;
		color: #FFFFFF;
		font-size: 26px;
		touch-action: none;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.animation-info {
		transition: left .25s ease;
	}

	.movable-area {
		width: 100%;
		height: 100%;
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 1 !important;
		pointer-events: none;
	}
</style>